import {
  Body,
  Controller,
  Get,
  Header,
  HttpCode,
  HttpException,
  HttpStatus,
  Post,
  Query,
  RawBodyRequest,
  Req,
  Res,
} from '@nestjs/common';
import { AppService } from './app.service';
import { ConfigService } from './cus-modules/config/config.service';
import AccessTokenDecorator from './decorator/AccessToken.decorator';
import { Request } from 'express';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly configService: ConfigService,
  ) {}

  @Post('/wx')
  @HttpCode(HttpStatus.OK)
  @Header('Content-Type', 'application/xml')
  async replyMessage(@Req() req: Request) {
    const parseXml = new Promise<string>((resolve, reject) => {
      let data = Buffer.from('');
      req.on('data', (chunk) => {
        data = Buffer.concat([data, chunk]);
      });

      req.on('end', () => {
        resolve(data.toString());
      });
      req.on('error', (e) => {
        reject(e);
      });
    });
    const data = await parseXml;
    return this.appService.replyMessage(data);
  }

  @Get('/wx')
  async validateAsWXServer(
    @Query('signature') signature: string,
    @Query('timestamp') timestamp: string,
    @Query('nonce') nonce: string,
    @Query('echostr') echostr: string,
  ) {
    return this.appService.validateAsWXServer(
      signature,
      timestamp,
      nonce,
      echostr,
    );
  }

  @Post('/api/wx')
  autoReply() {
    return 'replay';
  }

  @Get('/api/login')
  login(@AccessTokenDecorator() accessToken: string): any {
    console.log('accessToken', accessToken);
    return { accessToken };
  }

  @Post('/api/set_menu_button')
  setMenuButton(@AccessTokenDecorator() accessToken: string) {
    return this.appService.setMenuButton(accessToken);
  }
}
